package cn.Y_Qiu.user.controller;

import cn.Y_Qiu.basic.util.Ajaxresult;
import cn.Y_Qiu.basic.util.PageList;
import cn.Y_Qiu.user.domain.User;
import cn.Y_Qiu.user.domain.UserDto;
import cn.Y_Qiu.user.query.UserQuery;
import cn.Y_Qiu.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    // 添加
    @PutMapping
    public  Ajaxresult addOrUpdate(@RequestBody User user){
        try {
            if (user.getId() == null) {
                userService.add(user);
            } else {
                userService.update(user);
            }
            return Ajaxresult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return Ajaxresult.me().setMessage("炸了");
        }
    }

    // 删除
    @DeleteMapping("/{id}")
    public Ajaxresult delById(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return Ajaxresult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return Ajaxresult.me()
                    .setMessage("失败");
        }
    }
    // 查单
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.queryById(id);
    }
    // 查全
    @GetMapping
    public List<User> queryAll(){
        return userService.listAll();
    }
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery userQuery){
        return userService.queryPage(userQuery);
    }


    @PostMapping("/register/phone")
    public Ajaxresult register(@RequestBody UserDto userDto){
        System.out.println("到达controller");
        try {
            userService.phoneRegister(userDto);
            return Ajaxresult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return Ajaxresult.me().setMessage("失败");
        }
    }


    @PatchMapping
    public Ajaxresult patchremove(@RequestBody List<Long> ids){
        //System.out.println("到达controller");
        try {
            userService.patchremove(ids);
            return Ajaxresult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return Ajaxresult.me().setMessage("失败");
        }

    }

}
